package com.college.educenter.controller;

import com.college.commonutils.JwtUtils;
import com.college.educenter.entity.UcenterMember;
import com.college.educenter.service.UcenterMemberService;
import com.college.educenter.utils.ConstantPropertiesUtil;
import com.college.educenter.utils.HttpClientUtils;
import com.college.servicebase.exceptionhandler.CollegeException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@RequestMapping("/api/ucenter/wx")
@Controller
@CrossOrigin
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @GetMapping("/callback")
    public String callback(String code,String state) {
        try {
            //1、获取临时票据（code），类似于验证码
            //2、拿着code请求微信固定地址，得到access_token,openid
            //向认证服务器发送请求获取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
            "?appid=%s" +
            "&secret=%s" +
            "&code=%s" +
            "&grant_type=authorization_code";

            //生成qrcodeUrl
            String qrcodeUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            String info = HttpClientUtils.get(qrcodeUrl);

            //使用json转换工具gson
            Gson gson = new Gson();
            HashMap mapToken = gson.fromJson(info,HashMap.class);
            String access_token = (String) mapToken.get("access_token");
            String openid = (String) mapToken.get("openid");



            //把扫码人信息添加到数据库
            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member == null) {

                //拿到access_token和openid，再去请求微信固定地址，获取扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);;
                HashMap map = gson.fromJson(resultUserInfo, HashMap.class);
                String nickname = (String) map.get("nickname");
                String headimgurl = (String) map.get("headimgurl");


                member = new UcenterMember();
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                member.setNickname(nickname);
                memberService.save(member);
            }
            //使用jwt生成toeken字符串
            String token = JwtUtils.getJwtToken(member.getId(),member.getNickname());

            return "redirect:http://localhost:3000?token="+token;

        } catch (Exception e) {
            e.printStackTrace();
            throw new CollegeException(20001,"登录失败");
        }
    }

    //生成微信二维码
    @GetMapping("/login")
    public String getCode() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
        "?appid=%s" +
        "&redirect_uri=%s" +
        "&response_type=code" +
        "&scope=snsapi_login" +
        "&state=%s" +
        "#wechat_redirect";

        // 回调地址,使用urlEncode对链接进行处理
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new CollegeException(20001, e.getMessage());
        }

        //url
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "college");
        return "redirect:" + url;
    }
}
